from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.views.decorators.cache import cache_page
from paypal.standard.forms import PayPalPaymentsForm
from studenthoods.apps.shop.forms import OrderForm
from studenthoods.apps.shop.models import Shop, Order, HoodieColour
from studenthoods.apps.shop.utils import generate_order_hash, get_order_hash, \
    set_order_status
from time import strftime
import datetime
import settings

    
#@cache_page(60 * 15)    
def shop(request, slug_shop):
    now = datetime.datetime.now()
    shop = []
    form = []
    
    try:
        shop_exists = Shop.objects.get(slug=slug_shop)
    except Shop.DoesNotExist:
        raise Http404
    
    try: 
        shop = Shop.objects.filter(closing_date__gt=now, opening_date__lt=now).get(slug=slug_shop)
    except Shop.DoesNotExist:
        pass
    
    if shop:
        if request.method == 'POST':    
            form = OrderForm(shop, request.POST)
            
            if form.is_valid():
                order = Order()
                order.first_name = form.cleaned_data['first_name']
                order.surname = form.cleaned_data['surname']
                order.email = form.cleaned_data['email']
                order.phone_number = form.cleaned_data['phone_number']
                order.shop = shop
                order.size = form.cleaned_data['size']
                order.colour = form.cleaned_data['colour']
                            
                order.hash = generate_order_hash(strftime("%Y-%m-%d %H:%M:%S"), form.cleaned_data['email'], str(shop.id), form.cleaned_data['size'], form.cleaned_data['colour'])
                
                if shop.address_required:
                    order.address_line_1 = form.cleaned_data['address_line_1']
                    order.address_line_2 = form.cleaned_data['address_line_2']
                    order.city = form.cleaned_data['city']
                    order.postcode = form.cleaned_data['postcode']
                order.save()
                
                return redirect('shop_paypal', hash=order.hash)
        else:
            form = OrderForm(shop)
    
    return render_to_response('shop/templates/shop_step_1.html',
                              {'shop':shop, 
                               'form':form},
                              context_instance=RequestContext(request))

def sizes(request, slug_shop, slug_colour):
    sizes = []
    
    try:
        sizes = HoodieColour.objects.filter(shop__slug=slug_shop).get(slug=slug_colour).sizes()
    except:
        pass
    
    return render_to_response('shop/templates/size.ajax',
                             {'sizes':sizes,},
                             context_instance=RequestContext(request))

def paypal(request, hash):
    try:
        order = get_order_hash(hash)
    except Order.DoesNotExist:
        raise Http404

    try:
        shop = Shop.objects.get(id=order.shop.id)
    except Shop.DoesNotExist:
        raise Http404
    
    paypal_dict = {"business": settings.PAYPAL_RECEIVER_EMAIL,
                    "amount": shop.price,
                    "item_name": order.shop.name + ' in ' + order.colour +' size ' + order.size + ' delivered to ' + order.address + ' by StudentHoods',
                    "currency_code": "GBP",
                    "notify_url": order.url_notify,
                    "return_url": order.url_return,
                    "cancel_return": order.url_cancel_return,
                    "custom": order.hash, 
                    }

    form = PayPalPaymentsForm(initial=paypal_dict)
    
    return render_to_response('shop/templates/shop_step_2.html',
                              {'shop':shop,
                               'order':order, 
                               'form':form},
                              context_instance=RequestContext(request))

def paypal_cancel_return(request, hash):
    order = get_order_hash(hash)
    order.status = settings.ORDER_CANCELLED
    order.save()
    
    status = order.status
    
    return render_to_response('shop/templates/shop_step_3.html',
                      {'status': status},
                      context_instance=RequestContext(request))
    
def paypal_return(request, hash):
    order = get_order_hash(hash)
    status = order.status
    
    return render_to_response('shop/templates/shop_step_3.html',
                      {'status': status, 
                       'order': order},
                      context_instance=RequestContext(request))
